package demo4;

import java.util.Stack;

public class AfterStack {
    public int evalRPN(String[] str){
        Stack<Integer> stack=new Stack<>();
        for(String ch:str){
            if(!isOperator(ch)){
                int x=Integer.parseInt(ch);
                stack.push(x);
            }else{
                int val2=stack.pop();
                int val1=stack.pop();
                switch (ch){
                    case "+":
                        stack.push(val1+val2);
                        break;
                    case "-":
                        stack.push(val1-val2);
                        break;
                    case "*":
                        stack.push(val1*val2);
                        break;
                    case "/":
                        stack.push(val1/val2);
                        break;
                }
            }
        }
        if(stack.size()!=1){
            throw new RuntimeException("逆波兰表达式不合法！！");
        }

        System.out.println("逆波兰表达式的结果为："+stack.pop());
        return stack.pop();
    }
    private boolean isOperator(String str){
            if(str.equals("+")||str.equals("*")||str.equals("/")||str.equals("-")){
                return true;
            }

        return false;
    }
}
